﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using Warehouse.API.Applcation.Command.OutBoundCommand;
using Warehouse.Infrstructre.Interface;
using static WMSpublic.ParseAPI;
using WMSpublic;
using System.ComponentModel.DataAnnotations;
using Warehouse.Infrstructre;
using System.Data;
using Microsoft.EntityFrameworkCore;
using Warehouse.Domain;


namespace Warehouse.API.Applcation.CommandHandlers.OutShipCommandHandlers
{
    public class CreateOutShipCommandHandlers : IRequestHandler<CreateOutBoundCommand, int>
    {
        private readonly IOutShipRepository _outShipRepository;
        private readonly IOutProductRepository _outproduct;
        private readonly IMapper _mapper;
        private EFCoreDBcontext _dbContext;

        ApiResult<int> result = new ApiResult<int>();

        public CreateOutShipCommandHandlers(IOutShipRepository outShipRepository, IOutProductRepository outproduct, IMapper mapper, EFCoreDBcontext dbContext)
        {
            _outShipRepository = outShipRepository;
            _outproduct = outproduct;
            _mapper = mapper;
            _dbContext = dbContext;
        }

        public async Task<int> Handle(CreateOutBoundCommand request, CancellationToken cancellationToken)
        {
            //产品显示表
             List<Products> products =await GetProductsList(1,100);


            //销售产品关联表
            List<SellProduct> sellProducts = await GetSalesProductList(1,100);

            
             using(var tran = _dbContext.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {


                    // //判断库存
                    foreach (var item in request.OutBound.OPlist)
                    {
                        var stock = products.FirstOrDefault(x => x.ProductsID == item.ProductsID);
                        if (stock == null || stock.ProcurementNum < item.OutProuductNum)
                        {
                            return result.Data = -1;
                            //库存不足
                        }
                      
                    }


                    //存出库单
                    OutShip outShip = new OutShip()
                    {
                        OutShipId = request.OutBound.OutShipId,
                        OutShipCode = request.OutBound.OutShipCode,
                        ORremark = request.OutBound.ORremark,
                        OrderNumber = request.OutBound.OrderNumber,
                        OutShipType = request.OutBound.OutShipType,
                        ClientId = request.OutBound.ClientId,
                        ClientName = request.OutBound.ClientName,
                        Ccontact = request.OutBound.Ccontact,
                        VendorPhone = request.OutBound.VendorPhone,
                        MakePerson = request.OutBound.MakePerson,
                        MarkTime = request.OutBound.MarkTime,
                        SalesId = request.OutBound.SalesId,
                        user_id = request.OutBound.user_id,
                        office_id = request.OutBound.office_id,
                        AddName = request.OutBound.AddName,
                        AddTime = DateTime.Now,
                        AuditStart =1,
                    };

                    await _outShipRepository.AddAsync(outShip);

                    //出库产品
                    foreach (var op in request.OutBound.OPlist)
                    {
                        OutProduct outProduct = new OutProduct()
                        {
                           
                            OutShipId = outShip.OutShipId,
                            Batch = op.Batch,
                            OutPrice = op.OutPrice,
                            OutProuductNum = op.OutProuductNum,
                            ProductsID = op.ProductsID,
                            Binlocation = op.Binlocation,
                            office_id = op.office_id,
                            AddName = op.AddName,
                            AddTime = DateTime.Now,
                            user_id = op.user_id,
                        };
                        await _outproduct.AddAsync(outProduct);
                    }



                    //扣减库存

                    foreach (var item in request.OutBound.OPlist)
                    {
                        var res = products.FirstOrDefault(x => x.ProductsID == item.ProductsID);
                        res.ProcurementNum -= item.OutProuductNum;

                        //更新产品库存
                        var pro = _mapper.Map<UptPro>(res);
                        pro.ProductsID = res.ProductsID;

                        var stock = await UptProducts(pro);
                        if (stock != 1)
                        {
                            tran.Rollback(); //回滚扣减失败
                            return result.Data = -3;
                        }

                    }


                    //提交事务
                    tran.Commit();
                   
                    return 200;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
              
            }



        }


        /// <summary>
        /// 产品
        /// </summary>
        /// <returns></returns>
        public async Task<dynamic> GetProductsList(int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyOCIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMiwyIiwianRpIjoiNDMzMDY2ZGYtZjI2MC00MjY3LWJhZjktYmQzODFkZWFkYzBiIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6IuWwj-e-jiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3VyaSI6IiIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.F6NVEvAxW0LXOqPcIA8hWoL54BSxdIQTFtrJ9r0Ah18";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/cpd/api/ProductRead/GetAllProductInfo?pageindex=" + pindex + "&pagesize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }

        /// <summary>
        /// 产品更新
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public async Task<dynamic> UptProducts(UptPro pro)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyOCIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMiwyIiwianRpIjoiNDMzMDY2ZGYtZjI2MC00MjY3LWJhZjktYmQzODFkZWFkYzBiIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6IuWwj-e-jiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3VyaSI6IiIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.F6NVEvAxW0LXOqPcIA8hWoL54BSxdIQTFtrJ9r0Ah18";
            HttpClientWrapper cilent = new HttpClientWrapper(token);
            var Uptpro = JsonConvert.SerializeObject(pro);
            string upt = "http://116.205.121.197:8000/cpx/api/ProductInfo/ProductUpdateOutShip";
            string respose = await cilent.PostAsync(upt, Uptpro);
            var json = JsonConvert.DeserializeObject<ApiResult<int>>(respose);
            return json.Data; 
        }



        /// <summary>
        /// 销售产品
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetSalesProductList(int pageIndex,int pageSize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyOCIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMiwyIiwianRpIjoiNDMzMDY2ZGYtZjI2MC00MjY3LWJhZjktYmQzODFkZWFkYzBiIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6IuWwj-e-jiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3VyaSI6IiIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.F6NVEvAxW0LXOqPcIA8hWoL54BSxdIQTFtrJ9r0Ah18";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string sale = "http://116.205.121.197:8000/ywd/api/Sales/GetSalesList?pindex" + pageIndex + "&psize="+ pageSize;
            string repose = await cilent.GetAsync(sale);
            var json = JsonConvert.DeserializeObject<ApiResultList<SellProduct>>(repose);
            return json.data.list;
        }

        /// <summary>
        /// 入库产品
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetEnterStore(int pageIndex, int pageSize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyOCIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMiwyIiwianRpIjoiNDMzMDY2ZGYtZjI2MC00MjY3LWJhZjktYmQzODFkZWFkYzBiIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6IuWwj-e-jiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3VyaSI6IiIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.F6NVEvAxW0LXOqPcIA8hWoL54BSxdIQTFtrJ9r0Ah18";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string enter = "";
            string repose = await cilent.GetAsync(enter);
            var json = JsonConvert.DeserializeObject<ApiResultList<StockRoom>>(repose);
            return json.data.list;
        }


        //产品
        public class Products
        {
            /// <summary>
            /// 产品id
            /// </summary>
            public int ProductsID { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            public string? ProductsCode { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            public string? ProductsName { get; set; }
            /// <summary>
            /// 厂商编码
            /// </summary>
            public string? VendorsCode { get; set; }
            /// <summary>
            /// 内部编码
            /// </summary>
            public string? InteriorCode { get; set; }
            /// <summary>
            /// 规格
            /// </summary>
            public string? Specs { get; set; }
            /// <summary>
            /// 产品类别
            /// </summary>
            public int? ProductTypeID { get; set; }
            /// <summary>
            /// 存储单位
            /// </summary>
            public string? StorageUnits { get; set; }
            /// <summary>
            /// 预警（上）
            /// </summary>
            public int? Upperlimit { get; set; }
            /// <summary>
            /// 预警（下）
            /// </summary>
            public int? Lowerlimit { get; set; }
            /// <summary>
            /// 包装类型
            /// </summary>
            public int? WrapType { get; set; }
            /// <summary>
            /// 价格
            /// </summary>
            public decimal? Price { get; set; }
            /// <summary>
            /// 重量
            /// </summary>
            public decimal? Weight { get; set; }
            /// <summary>
            /// 默认仓库
            /// </summary>
            public int? WarehouseId { get; set; }
            /// <summary>
            /// 库位
            /// </summary>
            public int? StorehouseId { get; set; }
            /// <summary>
            /// 默认供应商
            /// </summary>
            public int? VendorId { get; set; }
            /// <summary>
            /// 默认客户
            /// </summary>
            public int? ClientId { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string? Describe { get; set; }
            /// <summary>
            /// 产品数量
            /// </summary>
            public int? ProcurementNum { get; set; }
            /// <summary>
            /// 公司id
            /// </summary>
            public string? Office_Id { get; set; }

            /// <summary>
            /// 用户id
            /// </summary>
            public int? User_Id { get; set; }
            /// <summary>
            /// 修改人姓名
            /// </summary>
            public string? UpdName { get; set; }

            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? UpdTime { get; set; } = DateTime.Now;
        }



        /// <summary>
        /// 销售产品关联表
        /// </summary>
        public class SellProduct
        {
            /// <summary>
            /// 销售产品关联表id
            /// </summary>
            
            public int SellProductId { get; set; }

            public int SalesId { get; set; }

            /// <summary>
            /// 销售编号
            /// </summary>
            public string? SalesCode { get; set; }

            /// <summary>
            /// 产品id
            /// </summary>
            public int? ProductsId { get; set; }

            /// <summary>
            /// 数量
            /// </summary>
            public int? SellProductNum { get; set; }

            /// <summary>
            /// 公司id
            /// </summary>
            public string? Office_Id { get; set; }

            /// <summary>
            /// 用户id
            /// </summary>
            public int? User_Id { get; set; }


        }


        /// <summary>
        /// 入库产品关联信息表
        /// </summary>
        public class StockProducts
        {
            /// <summary>
            /// 入库产品id
            /// </summary>
         
            public int StockProductId { get; set; }
            /// <summary>
            /// 入库id
            /// </summary>
            public int? StockId { get; set; }
            /// <summary>
            /// 产品id
            /// </summary>
            public int? ProductsID { get; set; }
            /// <summary>
            /// 批次
            /// </summary>
            public string? Batch { get; set; }
            /// <summary>
            /// 单价
            /// </summary>
            public decimal? Sprice { get; set; }
            /// <summary>
            /// 入库数
            /// </summary>
            public int? Quantity { get; set; }
            /// <summary>
            /// 库位
            /// </summary>
            public int? Binlocation { get; set; }
            /// <summary>
            /// 公司id
            /// </summary>
            public string? office_id { get; set; }
            /// <summary>
            /// 用户id
            /// </summary>
            public int? user_id { get; set; }

        }

        public class UptPro()
        {
            /// <summary>
            /// 产品id
            /// </summary>
            public int ProductsID { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            public string? ProductsCode { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            public string? ProductsName { get; set; }
            /// <summary>
            /// 厂商编码
            /// </summary>
            public string? VendorsCode { get; set; }
            /// <summary>
            /// 内部编码
            /// </summary>
            public string? InteriorCode { get; set; }
            /// <summary>
            /// 规格
            /// </summary>
            public string? Specs { get; set; }
            /// <summary>
            /// 产品类别
            /// </summary>
            public int? ProductTypeID { get; set; }
            /// <summary>
            /// 存储单位
            /// </summary>
            public string? StorageUnits { get; set; }
            /// <summary>
            /// 预警（上）
            /// </summary>
            public int? Upperlimit { get; set; }
            /// <summary>
            /// 预警（下）
            /// </summary>
            public int? Lowerlimit { get; set; }
            /// <summary>
            /// 包装类型
            /// </summary>
            public int? WrapType { get; set; }
            /// <summary>
            /// 价格
            /// </summary>
            public decimal? Price { get; set; }
            /// <summary>
            /// 重量
            /// </summary>
            public decimal? Weight { get; set; }
            /// <summary>
            /// 默认仓库
            /// </summary>
            public int? WarehouseId { get; set; }
            /// <summary>
            /// 库位
            /// </summary>
            public int? StorehouseId { get; set; }
            /// <summary>
            /// 默认供应商
            /// </summary>
            public int? VendorId { get; set; }
            /// <summary>
            /// 默认客户
            /// </summary>
            public int? ClientId { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string? Describe { get; set; }
            /// <summary>
            /// 产品数量
            /// </summary>
            public int? ProcurementNum { get; set; }
            /// <summary>
            /// 公司id
            /// </summary>
            public string? Office_Id { get; set; }

            /// <summary>
            /// 用户id
            /// </summary>
            public int? User_Id { get; set; }
            /// <summary>
            /// 修改人姓名
            /// </summary>
            public string? UpdName { get; set; }

            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? UpdTime { get; set; } = DateTime.Now;
 
            public string? ProductTypeName { get; set; }
            /// <summary>
            /// 供应商名称
            /// </summary>
            public string? VendorName { get; set; }
     
      
            public DateTime? AddTime { get; set; }
        }
    }
}
